package com.xbongbong.paas.service.dynamic.crm.strategy.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormDataDeleteBatchDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateBatchDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.service.dynamic.crm.strategy.AbstractDynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.CompetitorDynamicStrategy;
import com.xbongbong.parent.interfaces.DynamicStrategy;
import com.xbongbong.paas.service.dynamic.crm.strategy.MainBusinessDynamicStrategy;
import com.xbongbong.pro.businesstage.pojo.RequiredFieldPojo;
import com.xbongbong.pro.businesstage.pojo.dto.StageJumpDealDTO;
import com.xbongbong.pro.customercommunicate.pojo.dto.DynamicDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicArchiveDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicBatchAttrDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicCheckJoinTeamDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicDeleteDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicLabelDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicLinkOpportunityDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicSaveDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicStageJumpDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicUpdateBatchDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicUpdateDTO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.dictionary.OpportunityLossCauseEnum;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author gaojie
 * @version v1.0
 * @date 2022/8/23 09:45
 * @description
 */
@Service("competitorDynamicStrategyImpl")
public class CompetitorDynamicStrategyImpl extends AbstractDynamicStrategy implements DynamicStrategy, CompetitorDynamicStrategy, MainBusinessDynamicStrategy {

    private final Logger LOG = LoggerFactory.getLogger(CompetitorDynamicStrategyImpl.class);

    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private CompetitorModel competitorModel;
    @Resource
    private PaasFormModel paasFormModel;

    @Override
    public List<Integer> type() {
        return Arrays.asList(XbbRefTypeEnum.COMPETITOR.getCode());
    }

    @Override
    @Async("dynamicThreadPool")
    public void linkOpportunity(DynamicLinkOpportunityDTO dto) {
        try {
            String corpid = dto.getCorpid();
            Long opportunityId = dto.getOpportunityId();
            String userId = dto.getUserId();
            Long competitorId = dto.getCompetitorId();
            String memo = CrmLogMemoConstant.DYNAMIC_USER_LINK_OPPORTUNITY;
            // 竞争对手关联机会动态
            OpportunityEntityExt opportunity = opportunityModel.getByKey(opportunityId, corpid);
            Long opportunityFormId = opportunity.getFormId();
            String opportunityName = FastJsonHelper.getStringOrDefault(opportunity.getData(),SalesOpportunityEnum.NAME.getAttr(),"");
            PaasFormEntity opportunityPaasForm = paasFormModel.getByKey(opportunityFormId,corpid);
            List<String> compeitorMemoHolder = DynamicDTO.initMemoHolder(dto.getUserName(), opportunityPaasForm.getName(),opportunityName);
            DynamicDTO competitorDynamic = initDynamicDTO(userId, memo, ProjectLogEnum.COMPETITOR_UPDATE.getSubType(), compeitorMemoHolder, opportunityPaasForm, opportunityPaasForm.getSaasMark(), competitorId);
            // 设置关联业务
            competitorDynamic.setBusinessType(XbbRefTypeEnum.COMPETITOR.getCode());
            competitorDynamic.setRefId(dto.getOpportunityId());
            competitorDynamic.setRefBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
            competitorDynamic.setRefName(opportunityName);
            insertSimpleDynamic(Collections.singletonList(competitorDynamic),corpid);

            // 机会关联竞争对手动态
            CompetitorEntity competitor = competitorModel.getByKey(competitorId, corpid);
            Long competitorFormId = competitor.getFormId();
            String competitorName = FastJsonHelper.getStringOrDefault(competitor.getData(),CompetitorEnum.NAME.getAttr(),"");
            PaasFormEntity compeitorPaasForm = paasFormModel.getByKey(competitorFormId,corpid);
            List<String> opportunityMemoHolder  = DynamicDTO.initMemoHolder(dto.getUserName(), compeitorPaasForm.getName(),competitorName);
            DynamicDTO opportunityDynamic = initDynamicDTO(userId, memo, ProjectLogEnum.OPPORTUNITY_UPDATE.getSubType(), opportunityMemoHolder, compeitorPaasForm, compeitorPaasForm.getSaasMark(), opportunityId);
            // 设置关联业务
            opportunityDynamic.setBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
            opportunityDynamic.setRefId(competitorId);
            opportunityDynamic.setRefBusinessType(XbbRefTypeEnum.COMPETITOR.getCode());
            opportunityDynamic.setRefName(competitorName);
            insertDynamic(Collections.singletonList(opportunityDynamic),corpid);

        }catch (Exception e){
            LOG.error("CompetitorDynamicStrategyImpl#linkOpportunity  exception: {}",e);
        }

    }

    @Override
    @Async("dynamicThreadPool")
    public void cancelOpportunity(DynamicLinkOpportunityDTO dto) {
        try {
            String userId = dto.getUserId();
            String corpid = dto.getCorpid();
            Long opportunityId = dto.getOpportunityId();
            Long competitorId = dto.getCompetitorId();
            String userName = dto.getUserName();
            String memo = CrmLogMemoConstant.DYNAMIC_CANCLE_LINK_OPPORTUNITY;
            // 竞争对手 - 机会 动态
            OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(opportunityId, corpid);
            Long formId = opportunityEntityExt.getFormId();
            String opportunityName = FastJsonHelper.getStringOrDefault(opportunityEntityExt.getData(), SalesOpportunityEnum.NAME.getAttr(), "");
            // 获取表单信息
            PaasFormEntity opportunityPaasForm = paasFormModel.getByKey(formId,corpid);
            // 封装动态信息
            List<String> competiorMemoHolder = DynamicDTO.initMemoHolder(userName, opportunityPaasForm.getName(), opportunityName);
            DynamicDTO competitorDynamic = initDynamicDTO(userId, memo, ProjectLogEnum.COMPETITOR_UPDATE.getSubType(), competiorMemoHolder, opportunityPaasForm, opportunityPaasForm.getSaasMark(), competitorId);
            competitorDynamic.setBusinessType(XbbRefTypeEnum.COMPETITOR.getCode());
            // 设置关联信息
            competitorDynamic.setRefId(opportunityId);
            competitorDynamic.setRefBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
            competitorDynamic.setRefName(opportunityName);
            insertSimpleDynamic(Collections.singletonList(competitorDynamic),corpid);

            // 机会 - 竞争对手 动态
            CompetitorEntity competitor = competitorModel.getByKey(competitorId, corpid);
            String competitorName = FastJsonHelper.getStringOrDefault(competitor.getData(),CompetitorEnum.NAME.getAttr(),"");
            Long competitorFormId = competitor.getFormId();
            PaasFormEntity compeitorPaasForm = paasFormModel.getByKey(competitorFormId,corpid);
            List<String> opportunityMemoHolder = DynamicDTO.initMemoHolder(userName, compeitorPaasForm.getName(), competitorName);
            DynamicDTO opportunityDynamic = initDynamicDTO(userId, memo, ProjectLogEnum.OPPORTUNITY_UPDATE.getSubType(), opportunityMemoHolder, opportunityPaasForm, opportunityPaasForm.getSaasMark(), opportunityId);
            opportunityDynamic.setBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
            opportunityDynamic.setRefId(competitorId);
            opportunityDynamic.setRefName(competitorName);
            opportunityDynamic.setRefBusinessType(XbbRefTypeEnum.COMPETITOR.getCode());

            insertDynamic(Collections.singletonList(opportunityDynamic),corpid);
        }catch (Exception e){
            LOG.error("CompetitorDynamicStrategyImpl#cancelOpportunity exception: {}",e);
        }

    }

    @Override
    @Async("dynamicThreadPool")
    public void batchEditAttr(DynamicBatchAttrDTO dto) {
        try {

            List<Long> dataIdList = dto.getDataIdList();
            String corpid = dto.getCorpid();
            String userName = dto.getUserName();
            String userId = dto.getUserId();
            Long formId = null;
            Map<String, Object> params = new HashMap<>();
            params.put("corpid",corpid);
            params.put("ids",dataIdList);
            params.put("del", DelEnum.NORMAL.getDel());
            List<CompetitorEntity> competitorList = competitorModel.findEntitys(params);
            if (CollectionUtils.isNotEmpty(competitorList)) {
                CompetitorEntity competitor = competitorList.get(0);
                formId = competitor.getFormId();
            }

            Objects.requireNonNull(formId,"formId NullException");

            PaasFormEntity paasForm = getPaasForm(corpid,formId,XbbRefTypeEnum.COMPETITOR.getCode());
            //封装动态信息
            List<DynamicDTO> dynamicDTOList = dataIdList.stream().map(item -> {

                DynamicDTO dynamicDTO = DynamicDTO.initDynamicDTO(userId, CrmLogMemoConstant.DYNAMIC_USER_UPDATE_BASE_INFO, ProjectLogEnum.COMPETITOR_UPDATE.getSubType(),
                        DynamicDTO.initMemoHolder(userName, paasForm.getName()),
                        paasForm,
                        paasForm.getSaasMark()
                );
                dynamicDTO.setDataId(item);
                dynamicDTO.setBusinessType(XbbRefTypeEnum.COMPETITOR.getCode());
                return dynamicDTO;
            }).collect(Collectors.toList());
            //批量添加动态信息
            insertSimpleDynamic(dynamicDTOList,corpid);
        }catch (Exception e){

        }
    }

    @Override
    public void checkJoinTeam(DynamicCheckJoinTeamDTO dynamicCheckJoinTeamDTO) {

    }

    @Override
    @Async("dynamicThreadPool")
    public void update(DynamicUpdateDTO dynamicUpdateDTO) {
        try {
            FormDataUpdateDTO formDataUpdateDTO = dynamicUpdateDTO.getFormDataUpdateDTO();
            PaasFormDataEntity paasFormDataEntity = dynamicUpdateDTO.getBeforeUpdateVO().getPaasFormDataEntity();
            UpdateVO updateVO = dynamicUpdateDTO.getUpdateVO();
            PaasFormEntity paasForm = getPaasForm(formDataUpdateDTO.getCorpid(), paasFormDataEntity.getFormId(), formDataUpdateDTO.getBusinessType());
            //封装动态信息
            List<String> memoHolder = DynamicDTO.initMemoHolder(updateVO.getUserVO().getName(), paasForm.getName());
            DynamicDTO dynamicDTO = initDynamicDTO(updateVO.getUserVO().getName(),CrmLogMemoConstant.DYNAMIC_USER_UPDATE_COMPETITOR,ProjectLogEnum.COMPETITOR_UPDATE.getSubType(),
                    memoHolder,
                    paasForm,
                    formDataUpdateDTO.getSaasMark(),
                    paasFormDataEntity.getId());
            dynamicDTO.setBusinessType(paasForm.getBusinessType());
            //添加动态
            insertSimpleDynamic(Collections.singletonList(dynamicDTO),formDataUpdateDTO.getCorpid());
        }catch (Exception e){
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CompetitorDynamicStrategyImpl.update", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void batchUpdate(DynamicUpdateBatchDTO dynamicUpdateBatchDTO) {
        try {

            FormDataUpdateBatchDTO formDataUpdateBatchDTO = dynamicUpdateBatchDTO.getFormDataUpdateBatchDTO();
            List<Long> dataIdList = dynamicUpdateBatchDTO.getAllowUpdateDataIds();
            //获取基本信息
            String corpid = formDataUpdateBatchDTO.getCorpid();
            Long formId = formDataUpdateBatchDTO.getFormId();
            Integer businessType = formDataUpdateBatchDTO.getBusinessType();
            String userId = formDataUpdateBatchDTO.getUserId();
            String loginUserName = formDataUpdateBatchDTO.getLoginUserName();
            PaasFormEntity paasForm = getPaasForm(corpid,formId,businessType);
            //封装动态信息
            List<DynamicDTO> dynamicDTOList = dataIdList.stream().map(item -> {
                DynamicDTO dynamicDTO = DynamicDTO.initDynamicDTO(userId, CrmLogMemoConstant.DYNAMIC_USER_UPDATE_BASE_INFO, ProjectLogEnum.COMPETITOR_UPDATE.getSubType(),
                        DynamicDTO.initMemoHolder(loginUserName, paasForm.getName()),
                        paasForm,
                        formDataUpdateBatchDTO.getSaasMark()
                );
                dynamicDTO.setDataId(item);
                dynamicDTO.setBusinessType(XbbRefTypeEnum.COMPETITOR.getCode());
                return dynamicDTO;
            }).collect(Collectors.toList());
            //批量添加动态信息
            insertSimpleDynamic(dynamicDTOList,corpid);
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CompetitorDynamicStrategyImpl.batchUpdate", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void stageJump(DynamicStageJumpDTO dynamicStageJumpDTO){

        try {
            StageJumpDealDTO stageJumpDealDTO = dynamicStageJumpDTO.getStageJumpDealDTO();
            // 获取赢单竟品id
            List<RequiredFieldPojo> requiredField = stageJumpDealDTO.getRequiredField();
            RequiredFieldPojo winCompetitor = requiredField.stream().filter(item -> Objects.equals(item.getAttr(), SalesOpportunityEnum.WIN_COMPETITOR.getAttr())).findAny().orElse(null);
            // 没有填写赢单竟品不添加动态
            if (Objects.isNull(winCompetitor) || Objects.isNull(winCompetitor.getValue()) || StringUtils.isEmpty(winCompetitor.getValue().toString())) {
                return;
            }
            JSONArray winList = JSON.parseArray(JSON.toJSONString(winCompetitor.getValue()));
            if (Objects.isNull(winList) || winList.size() == 0){
                return;
            }
            Object winIdObj = winList.getJSONObject(0).get("id");
            if (Objects.isNull(winIdObj)){
                return;
            }
            String userId = stageJumpDealDTO.getUserId();
            Long winCompetitorId = Long.valueOf(winIdObj.toString());
            // 没有选择机会输单的赢单竟品，就不去保存动态了
            if (Objects.isNull(winCompetitorId) || winCompetitorId == 0){
                return;
            }
            PaasFormDataEntityExt paasFormDataEntityExt = dynamicStageJumpDTO.getPaasFormDataEntityExt();
            // 获取机会名称和表单
            JSONObject formData = paasFormDataEntityExt.getData();
            Long opportunityId = paasFormDataEntityExt.getDataId();
            String opportunityName = FastJsonHelper.getStringOrDefault(formData, SalesOpportunityEnum.NAME.getAttr(), "");
            Long formId = paasFormDataEntityExt.getFormId();
            String corpid = paasFormDataEntityExt.getCorpid();
            PaasFormEntity paasForm = getPaasForm(corpid, formId, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
            // 获取赢单竟品名称
            CompetitorEntity competitor = competitorModel.getByKey(winCompetitorId, corpid);
            JSONObject competitorData = competitor.getData();
            String competitorName = FastJsonHelper.getStringOrDefault(competitorData,CompetitorEnum.NAME.getAttr(),"");
            // 组装动态对象
            String memo = CrmLogMemoConstant.DYNAMIC_OPPORTUNITY_LOST_COMPETITOR;
            List<String> memoHolder = DynamicDTO.initMemoHolder(opportunityName, OpportunityLossCauseEnum.COMPETITOR_WIN.getName(), competitorName);
            DynamicDTO dynamicDTO = DynamicDTO.initDynamicDTO(userId, memo, ProjectLogEnum.COMPETITOR_CREATE.getSubType(), memoHolder, paasForm, paasForm.getSaasMark());
            dynamicDTO.setDataId(winCompetitorId);
            dynamicDTO.setBusinessType(XbbRefTypeEnum.COMPETITOR.getCode());
            dynamicDTO.setRefId(opportunityId);
            dynamicDTO.setRefBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
            dynamicDTO.setRefName(opportunityName);
            // 插入动态
            insertSimpleDynamic(Collections.singletonList(dynamicDTO),corpid);
        }catch (Exception e){
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CompetitorDynamicStrategyImpl.stageJump", e);
        }



    }

    @Override
    public void label(DynamicLabelDTO dynamicLabelDTO) {

    }

    @Override
    public void archive(DynamicArchiveDTO dynamicArchiveDTO) {

    }

    @Override
    @Async("dynamicThreadPool")
    public void save(DynamicSaveDTO dynamicSaveDTO) {
        try {
            SaasFormSaveDTO saasFormSaveDTO = dynamicSaveDTO.getSaasFormSaveDTO();
            UserEntity creator = dynamicSaveDTO.getCreator();
            Long dataId = dynamicSaveDTO.getDataId();
            Long formId = dynamicSaveDTO.getFormId();
            PaasFormEntity paasForm = getPaasForm(saasFormSaveDTO.getCorpid(), formId, saasFormSaveDTO.getBusinessType());

            String competitorName = FastJsonHelper.getStringOrDefaultFromFormData(saasFormSaveDTO.getNewData(), CompetitorEnum.NAME.getAttr(), "");


            String communicateMemo;
            List<String> memoPlaceHolder;
            //封装动态信息
            if (Objects.equals(saasFormSaveDTO.getIsImport(), BasicConstant.ONE)) {
                memoPlaceHolder = DynamicDTO.initMemoHolder(creator.getName(), competitorName);
                communicateMemo = CrmLogMemoConstant.DYNAMIC_USER_IMPORT;
            }else {
                memoPlaceHolder = DynamicDTO.initMemoHolder(creator.getName(),paasForm.getName(), competitorName);
                communicateMemo = CrmLogMemoConstant.DYNAMIC_USER_CREATE_COMPETITOR;
            }
            DynamicDTO dynamicDTO = initDynamicDTO(creator.getUserId(), communicateMemo, ProjectLogEnum.COMPETITOR_CREATE.getSubType(),
                    memoPlaceHolder,
                    paasForm,
                    paasForm.getSaasMark(),
                    dataId);
            dynamicDTO.setBusinessType(paasForm.getBusinessType());
            insertSimpleDynamic(Collections.singletonList(dynamicDTO),saasFormSaveDTO.getCorpid());
        }catch (Exception e){
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CompetitorDynamicStrategyImpl.save", e);
        }
    }

    @Override
    @Async("dynamicThreadPool")
    public void batchDelete(DynamicDeleteDTO dynamicDeleteDTO) {
        try {
            List<Long> allowDeleteDataIds = dynamicDeleteDTO.getAllowDeleteDataIds();
            FormDataDeleteBatchDTO formDataDeleteBatchDTO = dynamicDeleteDTO.getFormDataDeleteBatchDTO();
            PaasFormEntity paasForm = getPaasForm(formDataDeleteBatchDTO.getCorpid(), formDataDeleteBatchDTO.getFormId(), formDataDeleteBatchDTO.getBusinessType());
            //封装动态信息
            List<String> memoPlaceHolder = DynamicDTO.initMemoHolder(formDataDeleteBatchDTO.getLoginUserName(), paasForm.getName());
            List<DynamicDTO> dynamicDTOList = allowDeleteDataIds.stream().map(item -> {
                DynamicDTO dynamicDTO = initDynamicDTO(formDataDeleteBatchDTO.getUserId(), CrmLogMemoConstant.DYNAMIC_USER_DELETE,
                        ProjectLogEnum.COMPETITOR_DELETE.getSubType(),
                        memoPlaceHolder,
                        paasForm,
                        formDataDeleteBatchDTO.getSaasMark(),
                        item);
                return dynamicDTO;
            }).collect(Collectors.toList());
            //添加动态
            insertSimpleDynamic(dynamicDTOList,formDataDeleteBatchDTO.getCorpid());
        }catch (Exception e){
            LOG.error("com.xbongbong.paas.service.dynamic.crm.strategy.impl.CompetitorDynamicStrategyImpl.batchDelete", e);
        }
    }
}
